package com.bac.bacplatform;

import java.util.HashMap;
import java.util.Map;

import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.bac.javabeans.Principal;
import com.bac.utils.Config;
import com.bac.utils.Util;
import com.google.gson.Gson;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AddressActivity extends BaseActivity implements OnClickListener{
	private String addressString;
	
	private TextView mAddressTV;
	private EditText addressEditText;
	private Button confirmButton;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.personal_address);
		findViewById(R.id.title_left).setOnClickListener(this);
	}

	@Override
	public void init() {
		addressEditText = (EditText) findViewById(R.id.new_postaddress);
		mAddressTV = (TextView) findViewById(R.id.tv_address);
		
		confirmButton = (Button) findViewById(R.id.confirm_new_postaddress);
		confirmButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ChangePostAddress();
			}
		});
		
		getCurrentuser();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_left:
			finishActivityOut();
			break;
		default:
			break;
		}
	}
	
	public void ChangePostAddress(){
		Listener<String> sl = new Listener<String>() {

			@Override
			public void onResponse(String response) {
				dismissLoadingProgress();
				Log.i("TAG----success",response.toString());
				mAddressTV.setText(addressEditText.getText().toString());
				addressEditText.setText("");
				showToast("修改成功");
				Intent intent = new Intent(MainActivity.UPDATE_ACTION);
				sendBroadcast(intent);
				
			}
		};
		addressString = addressEditText.getText().toString().trim();
		if (addressString.length() <= 0) {
			showToast(R.string.input_new_postaddress);
			return;
		}
		showLoadingProgress();
		String path = Config.URL_CHANGE_POST_ADDRESS;
		Map<String, String> map = new HashMap<String, String>();
		map.put("address", addressString);
		Util.httpStringPost(path, sl, this, map);
	}
	
	public void getCurrentuser() {
		/**
		 * 成功返回结果
		 */
		Listener<String> sL = new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				dismissLoadingProgress();
				Log.i("TAG----success", response.toString());
				
				Gson gson = new Gson();
				Principal principal = gson.fromJson(response, Principal.class);
				if (principal.getAddress() != null ) {
					mAddressTV.setText(principal.getAddress());
				}
			}
		};
		showLoadingProgress();
		
		String path = Config.URL_CURRENT_USER;
		Util.httpRequestToGet(path, sL, this);
	}
}
